<template>
  <div class="site-map-container">
    <div class="map-header">
      <el-row :gutter="20" align="middle">
        <el-col :span="6">
          <el-select v-model="selectedCustomer" placeholder="选择客户" clearable @change="onCustomerChange">
            <el-option v-for="customer in customers" :key="customer.id" :label="customer.name" :value="customer.id" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button @click="refreshMarkers" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新标记
          </el-button>
        </el-col>
        <el-col :span="6">
          <el-button @click="toggleEditMode" :type="editMode ? 'danger' : 'primary'">
            <el-icon><Edit /></el-icon>
            {{ editMode ? '退出编辑' : '编辑模式' }}
          </el-button>
        </el-col>
        <el-col :span="6">
          <el-button @click="exportMapData" type="success">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
        </el-col>
      </el-row>
    </div>
    
         <div class="map-content" :class="{ 'edit-mode': editMode }">
       <div id="map-container" ref="mapContainer"></div>
     </div>
    
    <!-- 标记详情弹窗 -->
    <el-dialog v-model="markerDialogVisible" title="站点详情" width="600px">
      <div v-if="selectedMarker">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="站点名称">{{ selectedMarker.name }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">{{ getCustomerName(selectedMarker.customerId) }}</el-descriptions-item>
          <el-descriptions-item label="详细地址">{{ selectedMarker.address }}</el-descriptions-item>
          <el-descriptions-item label="坐标">{{ selectedMarker.latitude }}, {{ selectedMarker.longitude }}</el-descriptions-item>
          <el-descriptions-item label="标记描述" :span="2">{{ selectedMarker.markerDescription || '暂无描述' }}</el-descriptions-item>
        </el-descriptions>
        
                 <div v-if="editMode" class="marker-edit-form">
           <el-divider content-position="left">编辑标记</el-divider>
           <el-form :model="markerEditForm" :rules="markerEditRules" ref="markerEditFormRef" label-width="80px">
             <el-form-item label="标记颜色">
               <el-color-picker v-model="markerEditForm.markerColor" />
             </el-form-item>
             <el-form-item label="标记描述" prop="markerDescription">
               <el-input v-model="markerEditForm.markerDescription" type="textarea" :rows="3" placeholder="请输入标记描述" />
             </el-form-item>
             <el-form-item label="显示在地图">
               <el-switch v-model="markerEditForm.showOnMap" />
             </el-form-item>
             <el-form-item>
               <el-button type="primary" @click="saveMarkerEdit" :loading="saveLoading">保存</el-button>
               <el-button @click="cancelMarkerEdit">取消</el-button>
             </el-form-item>
           </el-form>
         </div>
      </div>
    </el-dialog>

         <!-- 添加标记弹窗 -->
     <el-dialog v-model="addMarkerDialogVisible" title="创建新站点" width="600px">
       <el-form :model="addMarkerForm" :rules="addMarkerRules" ref="addMarkerFormRef" label-width="100px">
         <el-form-item label="站点名称" prop="name">
           <el-input v-model="addMarkerForm.name" placeholder="请输入站点名称" />
         </el-form-item>
         <el-form-item label="站点地址" prop="address">
           <el-input v-model="addMarkerForm.address" placeholder="请输入站点地址" />
         </el-form-item>
         <el-form-item label="所属客户" prop="customerId">
           <el-select v-model="addMarkerForm.customerId" placeholder="请选择所属客户" style="width: 100%;">
             <el-option 
               v-for="customer in customers" 
               :key="customer.id" 
               :label="customer.name" 
               :value="customer.id"
             />
           </el-select>
         </el-form-item>
         <el-form-item label="纬度">
           <el-input v-model="addMarkerForm.latitude" placeholder="纬度" readonly />
         </el-form-item>
         <el-form-item label="经度">
           <el-input v-model="addMarkerForm.longitude" placeholder="经度" readonly />
         </el-form-item>
         <el-form-item label="标记颜色">
           <el-color-picker v-model="addMarkerForm.markerColor" />
         </el-form-item>
         <el-form-item label="标记描述">
           <el-input v-model="addMarkerForm.markerDescription" type="textarea" :rows="3" placeholder="请输入标记描述" />
         </el-form-item>
       </el-form>
       <template #footer>
         <span class="dialog-footer">
           <el-button @click="addMarkerDialogVisible = false">取消</el-button>
           <el-button type="primary" @click="confirmAddMarker" :loading="addLoading">创建站点</el-button>
         </span>
       </template>
     </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Refresh, Edit, Download } from '@element-plus/icons-vue';
import SiteAPI from '@/api/system/site.api';
import CustomerAPI from '@/api/system/customer.api';
import { mapConfig } from '@/config/map.js';

// 响应式数据
const mapContainer = ref(null);
const map = ref(null);
const markers = ref([]);
const customers = ref([]);
const sites = ref([]);
const selectedCustomer = ref(null);
const markerDialogVisible = ref(false);
const selectedMarker = ref(null);
const editMode = ref(false);
const loading = ref(false);
const saveLoading = ref(false);
const addLoading = ref(false);
const addMarkerDialogVisible = ref(false);

// 表单数据
const markerEditForm = ref({
  markerColor: '#FF0000',
  markerDescription: '',
  showOnMap: true
});

// 编辑表单验证规则
const markerEditRules = {
  markerDescription: [
    { max: 500, message: '描述不能超过500个字符', trigger: 'blur' }
  ]
};

const addMarkerForm = ref({
  name: '',
  address: '',
  latitude: null,
  longitude: null,
  markerColor: '#FF0000',
  markerDescription: '',
  customerId: null
});

const addMarkerRules = {
  name: [
    { required: true, message: '请输入站点名称', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback()
          return
        }
        // 检查名称是否已存在（排除当前编辑的站点）
        const existingSite = sites.value.find(site => 
          site.name === value && site.id !== addMarkerForm.value.id
        )
        if (existingSite) {
          callback(new Error('站点名称已存在，请使用其他名称'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  address: [
    { required: true, message: '请输入站点地址', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback()
          return
        }
        // 检查地址是否已存在（排除当前编辑的站点）
        const existingSite = sites.value.find(site => 
          site.address === value && site.id !== addMarkerForm.value.id
        )
        if (existingSite) {
          callback(new Error('站点地址已存在，请使用其他地址'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
};

const addMarkerFormRef = ref();
const markerEditFormRef = ref();

// 计算属性 - 移除不需要的计算属性

// 加载百度地图API
const loadBaiduMapAPI = () => {
  return new Promise((resolve, reject) => {
    // 检查是否已经加载
    if (window.BMap) {
      resolve();
      return;
    }

    // 创建script标签
    const script = document.createElement('script');
    script.src = `https://api.map.baidu.com/api?v=3.0&ak=${mapConfig.baidu.ak}&callback=initBaiduMap`;
    script.async = true;
    
    // 定义回调函数
    window.initBaiduMap = () => {
      resolve();
    };
    
    script.onerror = () => {
      reject(new Error('百度地图API加载失败'));
    };
    
    document.head.appendChild(script);
  });
};

// 地图初始化
const initMap = async () => {
  try {
    // 先加载百度地图API
    await loadBaiduMapAPI();
    
    // 初始化百度地图
    map.value = new BMap.Map(mapContainer.value);
    const point = new BMap.Point(mapConfig.baidu.defaultCenter.lng, mapConfig.baidu.defaultCenter.lat);
    map.value.centerAndZoom(point, mapConfig.baidu.defaultZoom);
    map.value.enableScrollWheelZoom();
    
    // 添加地图控件
    map.value.addControl(new BMap.NavigationControl());
    map.value.addControl(new BMap.ScaleControl());
    map.value.addControl(new BMap.OverviewMapControl());
    
         // 添加点击事件
map.value.addEventListener('click', (e) => {
  if (editMode.value) {
    // 检查是否点击了现有标记
    const clickedMarker = markers.value.find(({ marker }) => {
      const markerPoint = marker.getPosition();
      const clickPoint = e.point;
      const distance = Math.sqrt(
        Math.pow(markerPoint.lng - clickPoint.lng, 2) + 
        Math.pow(markerPoint.lat - clickPoint.lat, 2)
      );
      return distance < 0.002; // 增大点击范围阈值，更容易点击到标记
    });
    
    if (clickedMarker) {
      // 点击了现有标记，不在这里处理，让标记自己的点击事件处理
      return;
    } else {
      // 点击了空白区域，显示创建新站点对话框
      showAddMarkerDialog(e.point);
    }
  } else {
    // 非编辑模式下，检查是否点击了标记
    const clickedMarker = markers.value.find(({ marker }) => {
      const markerPoint = marker.getPosition();
      const clickPoint = e.point;
      const distance = Math.sqrt(
        Math.pow(markerPoint.lng - clickPoint.lng, 2) + 
        Math.pow(markerPoint.lat - clickPoint.lat, 2)
      );
      return distance < 0.002;
    });
    
    if (clickedMarker) {
      // 点击了标记，不在这里处理，让标记自己的点击事件处理
      return;
    }
  }
});
  } catch (error) {
    console.error('地图初始化失败:', error);
    ElMessage.error('地图加载失败，请检查网络连接');
  }
};

// 加载客户列表
const loadCustomers = async () => {
  try {
    const res = await CustomerAPI.getPage({ currentPage: 1, pageSize: 1000 });
    customers.value = res.records || [];
  } catch (error) {
    console.error('加载客户列表失败:', error);
    ElMessage.error('加载客户列表失败');
  }
};

// 加载站点列表
const loadSites = async () => {
  try {
    const res = await SiteAPI.getPage({ currentPage: 1, pageSize: 1000 });
    sites.value = res.records || [];
  } catch (error) {
    console.error('加载站点列表失败:', error);
    ElMessage.error('加载站点列表失败');
  }
};

// 加载地图标记
const loadMarkers = async () => {
  loading.value = true;
  try {
    const params = selectedCustomer.value ? { customerId: selectedCustomer.value } : {};
    console.log('请求地图标记参数:', params);
    
    const res = await SiteAPI.getMapMarkers(params);
    console.log('地图标记响应:', res);
    
    // 清除现有标记
    clearMarkers();
    
    // 添加新标记
    if (res && Array.isArray(res)) {
      res.forEach(site => {
        if (site.latitude && site.longitude) {
          addMarker(site);
        }
      });
      console.log(`成功加载 ${res.length} 个标记`);
    } else {
      console.warn('地图标记数据格式不正确:', res);
    }
  } catch (error) {
    console.error('加载地图标记失败:', error);
    ElMessage.error(`加载地图标记失败: ${error.message || '未知错误'}`);
  } finally {
    loading.value = false;
  }
};

// 添加标记
const addMarker = (site) => {
  if (!window.BMap) {
    console.warn('百度地图API未加载');
    return;
  }
  
  const point = new BMap.Point(site.longitude, site.latitude);
  
  // 创建自定义标记图标
  const createCustomIcon = (color = '#FF0000') => {
    const size = new BMap.Size(32, 32);
    const imageOffset = new BMap.Size(0, 0);
    const iconAnchor = new BMap.Size(16, 32);
    
    // 创建SVG图标 - 更美观的标记样式
    const svgIcon = `
      <svg width="32" height="32" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <filter id="shadow" x="-50%" y="-50%" width="200%" height="200%">
            <feDropShadow dx="0" dy="2" stdDeviation="2" flood-color="rgba(0,0,0,0.3)"/>
          </filter>
        </defs>
        <path d="M16 2C9.373 2 4 7.373 4 14c0 8 12 18 12 18s12-10 12-18c0-6.627-5.373-12-12-12z" 
              fill="${color}" stroke="#ffffff" stroke-width="1.5" filter="url(#shadow)"/>
        <circle cx="16" cy="12" r="3" fill="#ffffff"/>
        <circle cx="16" cy="12" r="1.5" fill="${color}"/>
      </svg>
    `;
    
    const dataURL = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgIcon)));
    
    return new BMap.Icon(dataURL, size, {
      imageOffset: imageOffset,
      anchor: iconAnchor
    });
  };
  
  // 创建标记
  const marker = new BMap.Marker(point, {
    icon: createCustomIcon(site.markerColor || '#FF0000')
  });
  
  // 添加点击事件
  marker.addEventListener('click', (e) => {
    // 阻止事件冒泡到地图
    e.domEvent.stopPropagation();
    
    if (editMode.value) {
      // 编辑模式下，直接显示编辑对话框
      selectedMarker.value = site;
      markerEditForm.value = {
        markerColor: site.markerColor || '#FF0000',
        markerDescription: site.markerDescription || '',
        showOnMap: site.showOnMap !== false
      };
      markerDialogVisible.value = true;
    } else {
      // 非编辑模式下，显示信息窗口
      map.value.openInfoWindow(infoWindow, point);
    }
  });
  
  // 添加鼠标悬停效果，在编辑模式下显示提示
  if (editMode.value) {
    marker.addEventListener('mouseover', () => {
      marker.setCursor('pointer');
    });
  }
  
  // 添加信息窗口
  const infoWindow = new BMap.InfoWindow(`
    <div style="padding: 15px; min-width: 200px;">
      <h4 style="margin: 0 0 10px 0; color: #333;">${site.name}</h4>
      <p style="margin: 5px 0; color: #666;"><strong>地址：</strong>${site.address || '暂无地址'}</p>
      <p style="margin: 5px 0; color: #666;"><strong>客户：</strong>${getCustomerName(site.customerId)}</p>
      ${site.markerDescription ? `<p style="margin: 5px 0; color: #666;"><strong>描述：</strong>${site.markerDescription}</p>` : ''}
      <p style="margin: 5px 0; color: #999; font-size: 12px;">坐标：${site.latitude}, ${site.longitude}</p>
    </div>
  `);
  
  map.value.addOverlay(marker);
  markers.value.push({ marker, site });
};

// 清除标记
const clearMarkers = () => {
  if (!map.value) return;
  
  markers.value.forEach(({ marker }) => {
    map.value.removeOverlay(marker);
  });
  markers.value = [];
};

// 客户选择变化
const onCustomerChange = () => {
  loadMarkers();
};

// 刷新标记
const refreshMarkers = () => {
  loadMarkers();
};

// 切换编辑模式
const toggleEditMode = () => {
  editMode.value = !editMode.value;
  if (editMode.value) {
    ElMessage.success('已进入编辑模式：点击红色标记编辑，点击空白区域创建新站点');
  } else {
    ElMessage.info('已退出编辑模式');
  }
};

// 显示添加标记对话框
const showAddMarkerDialog = (point) => {
  addMarkerForm.value = {
    name: '',
    address: '',
    latitude: point.lat,
    longitude: point.lng,
    markerColor: '#FF0000',
    markerDescription: '',
    customerId: selectedCustomer.value || (customers.value.length > 0 ? customers.value[0].id : null)
  };
  addMarkerDialogVisible.value = true;
};

// 确认添加标记
const confirmAddMarker = async () => {
  try {
    await addMarkerFormRef.value.validate();
    
    addLoading.value = true;
    
    // 创建新站点
    const newSite = {
      name: addMarkerForm.value.name,
      address: addMarkerForm.value.address,
      customerId: addMarkerForm.value.customerId,
      latitude: addMarkerForm.value.latitude,
      longitude: addMarkerForm.value.longitude,
      markerColor: addMarkerForm.value.markerColor,
      markerDescription: addMarkerForm.value.markerDescription,
      showOnMap: true
    };
    
    await SiteAPI.create(newSite);
    ElMessage.success('站点创建成功');
    addMarkerDialogVisible.value = false;
    
    // 重新加载站点列表和标记
    loadSites();
    loadMarkers();
  } catch (error) {
    console.error('创建站点失败:', error);
    ElMessage.error('创建站点失败: ' + (error.message || '未知错误'));
  } finally {
    addLoading.value = false;
  }
};

// 保存标记编辑
const saveMarkerEdit = async () => {
  try {
    // 验证表单
    await markerEditFormRef.value.validate();
    
    saveLoading.value = true;
    
    const updatedSite = {
      ...selectedMarker.value,
      markerColor: markerEditForm.value.markerColor,
      markerDescription: markerEditForm.value.markerDescription,
      showOnMap: markerEditForm.value.showOnMap
    };
    
    await SiteAPI.updateSiteMapInfo(updatedSite.id, updatedSite);
    ElMessage.success('标记信息更新成功');
    markerDialogVisible.value = false;
    
    // 重新加载标记以更新图标
    loadMarkers();
  } catch (error) {
    if (error.message && error.message.includes('验证失败')) {
      // 表单验证失败，不显示错误消息
      return;
    }
    console.error('标记信息更新失败:', error);
    ElMessage.error('标记信息更新失败: ' + (error.message || '未知错误'));
  } finally {
    saveLoading.value = false;
  }
};

// 取消标记编辑
const cancelMarkerEdit = () => {
  markerDialogVisible.value = false;
};

// 导出地图数据
const exportMapData = () => {
  const mapData = sites.value.filter(site => site.latitude && site.longitude);
  const dataStr = JSON.stringify(mapData, null, 2);
  const dataBlob = new Blob([dataStr], { type: 'application/json' });
  const url = URL.createObjectURL(dataBlob);
  const link = document.createElement('a');
  link.href = url;
  link.download = 'map-data.json';
  link.click();
  URL.revokeObjectURL(url);
  ElMessage.success('地图数据导出成功');
};

// 获取客户名称
const getCustomerName = (customerId) => {
  const customer = customers.value.find(c => c.id === customerId);
  return customer ? customer.name : '未知客户';
};

// 生命周期
onMounted(async () => {
  await initMap();
  loadCustomers();
  loadSites();
  loadMarkers();
});

onUnmounted(() => {
  if (map.value) {
    map.value.clearOverlays();
  }
});
</script>

<style scoped>
.site-map-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.map-header {
  padding: 15px;
  background: #f5f5f5;
  border-bottom: 1px solid #ddd;
}

.map-content {
  flex: 1;
  position: relative;
}

#map-container {
  width: 100%;
  height: 100%;
  min-height: 600px;
}

.marker-edit-form {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 地图标记样式 */
:deep(.BMap_Marker) {
  cursor: pointer;
  transition: transform 0.2s ease;
}

:deep(.BMap_Marker:hover) {
  transform: scale(1.1);
}

/* 编辑模式下的标记样式 */
.edit-mode :deep(.BMap_Marker) {
  cursor: pointer;
  transition: all 0.3s ease;
}

.edit-mode :deep(.BMap_Marker:hover) {
  transform: scale(1.2);
  filter: brightness(1.2);
}

/* 信息窗口样式 */
:deep(.BMap_bubble_title) {
  font-weight: bold;
  color: #333;
}

:deep(.BMap_bubble_content) {
  color: #666;
}
</style> 